(function() {
  app.service('kchart', ['$rootScope', '$window', 'quoteApi', function($rootScope, $window, quoteApi) {
    this.canvas2 = function(obj) {
      angular.element(document).ready(function() {
        var k_chart_write = $('#k-chart-write');
        k_chart_write.attr('width', $(window).get(0).innerWidth * 0.98 * 4);
        k_chart_write.attr('height', k_chart_write.innerWidth() * 0.74);
        $('#buttons_opear').show();
        $('#buttons_opear').css('top', k_chart_write.parent().innerWidth() * 0.4 + 1.5);

        var config_zoom = {
          num: 50,
        };
        obj.page_size = 120;

        $('#add_add').off();
        $('#rec_rec').off();
        $('#add_add').on('click', function() {
          if (config_zoom.num == 20) return;
          config_zoom.num = config_zoom.num - 10;
          kChartcanvas(obj);
        });
        $('#rec_rec').on('click', function() {
          if (config_zoom.num == 50) return;
          config_zoom.num = config_zoom.num + 10;
          kChartcanvas(obj);
        });

        kChartcanvas(obj);

        function kChartcanvas(obj) {
          var canvasw = k_chart_write.innerWidth() - 5;
          var canvash = k_chart_write.innerHeight() - 40;
          obj.sublist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
          var k = new quoteApi.QuoteApi.Kline0x22(obj);
          quoteApi.query(k).then(function(data) {
            var transData = {};
            var transData_data = [];
            var dataa = [];
            data.detail instanceof Array ? dataa = data.detail : dataa[0] = data.detail;
            for (var i = 0; i < dataa.length; i++) {
              var arr1 = [];
              arr1[0] = (dataa)[i].date;
              arr1[1] = (dataa)[i].open;
              arr1[2] = (dataa)[i].hight;
              arr1[3] = (dataa)[i].low;
              arr1[4] = (dataa)[i].cur;
              arr1[5] = (dataa)[i].amount;
              arr1[6] = (dataa)[i].volume;
              arr1[7] = ((dataa)[i].swap) / 10000;
              transData_data.push(arr1);
            }
            transData.data = transData_data;
            var data = transData;
            var co = document.getElementById('k-chart-write');
            var imgData = null; //保存的画布数据
            var oGc = co.getContext('2d');
            oGc.clearRect(0, 0, 110000, 10000);
            var n = data.data.length;
            var nv = n;
            var ns = 0;
            var lineleft = canvasw * 0.94 / config_zoom.num;
            var codeinfoArr = [];
            var avg_priceArr = []; //5,10,20,60
            var maxMinObj = {};
            var Rectwidth = lineleft - canvasw * 0.88 / 200;
            var last_height = $('.container-fluid').height() || 0;
            var nStartX = 0;
            var zuobiao = []; // 点击时的坐标
            var xline = false; //X线是否能拖动；
            var yline = false; //y线是否能拖动；
            var pre_next = 0;
            canvaspath(n);
            $('#pre_pre').off();
            $('#next_next').off();
            $(co).off();

            $('#pre_pre').on('click', function() {
              if (pre_next >= n - config_zoom.num) return;
              pre_next++;
              ns = nv - pre_next;
              if (ns > n) {
                ns = n;
              }
              if (n > 180) {
                if (ns < 60) {
                  ns = 60;
                }
              } else {
                if (n < config_zoom.num) {
                  ns = n;
                }
              }
              if (n > config_zoom.num && ns <= config_zoom.num) {
                ns = config_zoom.num;
              }
              canvaspath(ns);
            });
            $('#next_next').on('click', function() {
              if (pre_next == 0) return;
              pre_next--;
              ns = nv - pre_next;
              if (ns > n) {
                ns = n;
              }
              if (n > 180) {
                if (ns < 60) {
                  ns = 60;
                }
              } else {
                if (n < config_zoom.num) {
                  ns = n;
                }
              }
              if (n > config_zoom.num && ns <= config_zoom.num) {
                ns = config_zoom.num;
              }
              canvaspath(ns);
            });


            $(co).on('touchstart', function(e) {
              nStartX = e.targetTouches[0].pageY;
              var _x = e.targetTouches[0].pageX;
              var _y = nStartX - last_height;
              if (zuobiao[0] - _x * 4 >= -60 && zuobiao[0] - _x * 4 <= 60) {
                xline = true;
              } else {
                xline = false;
              }
              // console.log(_y);
              // if (zuobiao[1] - _y * 4 >= -60 && zuobiao[1] - _y * 4 <= 60) {
              //   yline = true;
              // } else {
              //   yline = false;
              // }
            });
            $(co).on('click', function(ev) {
              var x, y;
              x = ev.layerX || ev.offsetX;
              y = ev.layerY || ev.offsetY;
              //canvas 实际上的坐标
              x = x * 4;
              var clickIndex = Math.ceil((x - canvasw * 0.06) / lineleft);
              if (clickIndex < 0) clickIndex = 0;
              if (clickIndex >= codeinfoArr.length) clickIndex = codeinfoArr.length - 1;
              var check_data = codeinfoArr[clickIndex];
              x = (clickIndex) * lineleft + canvasw * 0.04 + Rectwidth / 2;
              x >= canvasw * 0.98 ? x = canvasw * 0.98 : '';
              zuobiao[1] = y;
              zuobiao[0] = x;
              var open = check_data[1];
              var now = check_data[4];
              var low = check_data[3];
              var hight = check_data[2];
              var close = check_data[8];
              var hsl = check_data[7];
              $rootScope.$apply(function() {
                $rootScope.detail_order = {
                  now: now,
                  height: hight,
                  open: open,
                  low: low,
                  zde: (now - open),
                  dev_h: (now - open) / open,
                  vol: check_data[6],
                  amount: check_data[5],
                  close: close,
                  hsl: hsl
                };
                $rootScope.$broadcast('AddressUpdated');
              });
              oGc.clearRect(0, 0, canvasw + 10, canvash + 100);
              oGc.putImageData(imgData, 0, 0, 0, 0, canvasw + 10, canvash + 100);
              oGc.beginPath();
              oGc.lineWidth = 4;
              oGc.strokeStyle = '#888888';
              oGc.moveTo(x, canvash * 0.09);
              oGc.lineTo(x, canvash * 0.65 + canvash / 3);
              oGc.stroke();
              oGc.closePath();
              oGc.beginPath();
              oGc.moveTo(canvasw * 0.04, (5 + canvash * 0.09 + canvash * 0.46 / (maxMinObj.maxk - maxMinObj.mink) * (maxMinObj.maxk - check_data[4])));
              oGc.lineTo(canvasw * 0.98, (5 + canvash * 0.09 + canvash * 0.46 / (maxMinObj.maxk - maxMinObj.mink) * (maxMinObj.maxk - check_data[4])));
              oGc.stroke();
              oGc.closePath();
              drawfont('40px', oGc, codeinfoArr[clickIndex][0], canvasw * 0.45, canvash * 1 + 30);
              drawfont('40px', oGc, check_data[4].toFixed(2), canvasw * 0.04, (5 + canvash * 0.09 + canvash * 0.46 / (maxMinObj.maxk - maxMinObj.mink) * (maxMinObj.maxk - check_data[4])) - 20);
            });
            $(co).on('touchmove', function(evt) {
              evt.preventDefault();
              var x, y;
              var touch = evt.changedTouches[0]; //获取第一个触点
              var _x = Number(touch.pageX) * 4; //页面触点X坐标
              var _y = Number(touch.pageY - last_height) * 4; //页面触点Y坐标
              var clickIndex = Math.ceil((_x - canvasw * 0.06 - 1) / lineleft);
              if (clickIndex < 0) clickIndex = 0;
              if (clickIndex >= codeinfoArr.length) clickIndex = codeinfoArr.length - 1;
              var check_data = codeinfoArr[clickIndex];
              zuobiao[0] = _x;
              zuobiao[1] = (5 + canvash * 0.09 + canvash * 0.46 / (maxMinObj.maxk - maxMinObj.mink) * (maxMinObj.maxk - check_data[4]));
              if (xline) {
                oGc.clearRect(0, 0, canvasw + 10, canvash + 100);
                oGc.putImageData(imgData, 0, 0, 0, 0, canvasw + 10, canvash + 100);
                _x <= canvasw * 0.04 ? _x = canvasw * 0.04 : '';
                _x >= canvasw * 0.98 ? _x = canvasw * 0.98 : '';
                if (_x > clickIndex * (lineleft + 1) + canvasw * 0.04 + lineleft / 3) { _x = clickIndex * (lineleft + 1) + canvasw * 0.04 + lineleft / 3; }
                oGc.beginPath();
                oGc.lineWidth = 4;
                oGc.strokeStyle = '#888888';
                oGc.moveTo(_x, 0.5);
                oGc.lineTo(_x, canvash * 0.65 + canvash / 3);
                oGc.stroke();
                oGc.moveTo(canvasw * 0.04, (5 + canvash * 0.09 + canvash * 0.46 / (maxMinObj.maxk - maxMinObj.mink) * (maxMinObj.maxk - check_data[4])));
                oGc.lineTo(canvasw * 0.98, (5 + canvash * 0.09 + canvash * 0.46 / (maxMinObj.maxk - maxMinObj.mink) * (maxMinObj.maxk - check_data[4])));
                oGc.stroke();
                oGc.closePath();
                drawfont('40px', oGc, check_data[4].toFixed(2), canvasw * 0.04, (5 + canvash * 0.09 + canvash * 0.46 / (maxMinObj.maxk - maxMinObj.mink) * (maxMinObj.maxk - check_data[4])) - 20);
                drawfont('40px', oGc, codeinfoArr[clickIndex][0], canvasw * 0.45, canvash * 1 + 30);
                var price5 = avg_priceArr[0][clickIndex];
                var price10 = avg_priceArr[1][clickIndex];
                var price20 = avg_priceArr[2][clickIndex];
                var price60 = avg_priceArr[3][clickIndex];
                oGc.clearRect(0, 0, canvasw, canvash * 0.09);
                drawfont('40px', oGc, 'MA' + 5 + ':' + price5, canvasw * 0.04, canvash * 0.05, '#ff52fa');
                drawfont('40px', oGc, 'MA' + 10 + ':' + price10, canvasw * 0.04 + canvasw / 4, canvash * 0.05, '#f5bc49');
                drawfont('40px', oGc, 'MA' + 20 + ':' + price20, canvasw * 0.04 + canvasw / 4 * 2, canvash * 0.05, '#599ced');
                drawfont('40px', oGc, 'MA' + 60 + ':' + price60, canvasw * 0.04 + canvasw / 4 * 3, canvash * 0.05, '#888888');
                var open = check_data[1];
                var now = check_data[4];
                var low = check_data[3];
                var hight = check_data[2];
                var close;
                close = check_data[8];
                var hsl = check_data[7];
                $rootScope.$apply(function() {
                  $rootScope.detail_order = {
                    now: now,
                    height: hight,
                    open: open,
                    low: low,
                    zde: (now - open),
                    dev_h: (now - open) / open,
                    vol: check_data[6],
                    amount: check_data[5],
                    close: close,
                    hsl: hsl
                  };
                  $rootScope.$broadcast('AddressUpdated');
                });
                return;
              }
              if (yline) {
                oGc.clearRect(0, 0, canvasw + 10, canvash + 100);
                oGc.putImageData(imgData, 0, 0, 0, 0, canvasw + 10, canvash + 100);
                _y <= canvash * 0.09 ? _y = canvash * 0.09 : ' ';
                _y >= canvash * 0.57 ? _y = canvash * 0.57 : ' ';
                oGc.beginPath();
                oGc.lineWidth = 4;
                oGc.strokeStyle = '#000000';
                oGc.moveTo(_x, canvash * 0.09);
                oGc.lineTo(_x, canvash * 0.65 + canvash / 3);
                oGc.stroke();
                oGc.beginPath();
                oGc.lineWidth = 5;
                oGc.strokeStyle = '#000000';
                oGc.moveTo(canvasw * 0.04, _y);
                oGc.lineTo(canvasw * 0.98, _y);
                oGc.stroke();
                oGc.closePath();
                drawfont('40px', oGc, (((canvash * 0.57 - _y) / (canvash * 0.48)) * (maxMinObj.maxk - maxMinObj.mink) + maxMinObj.mink).toFixed(2), canvasw * 0.04, ((_y - canvash * 0.09) / (canvash * 0.48)) * (canvash * 0.48) + canvash * 0.09);
                return;
              }
              // zuobiao = [];
              var c = Math.round((evt.changedTouches[0].pageX - nStartX) / Rectwidth);
              ns = nv - c;
              if (ns > n) {
                ns = n;
              }
              if (n > 180) {
                if (ns < 60) {
                  ns = 60;
                }
              } else {
                if (n < config_zoom.num) {
                  ns = n;
                }
              }
              if (n > config_zoom.num && ns <= config_zoom.num) {
                ns = config_zoom.num;
              }
              // co.width = co.width;
              canvaspath(ns);
            });
            $(co).on('touchend', function(e) {
              if (xline || yline) return;
              nv = ns;
            });

            function canvaspath(n) {
              codeinfoArr = [];
              avg_priceArr = [];
              imgData = null;
              oGc.clearRect(0, 0, canvasw + 10, canvash + 100);
              var nlength = n > config_zoom.num ? config_zoom.num : n;
              var maxk = 0,
                maxl = 0;
              var mink = 1 / 0,
                minl = 0;
              //生成两个矩形框
              oGc.strokeStyle = '#000';
              oGc.strokeRect(canvasw * 0.04, canvash * 0.09, canvasw * 0.94, canvash * 0.48);
              oGc.strokeRect(canvasw * 0.04, canvash * 0.65, canvasw * 0.94, canvash / 3);
              //生成十字虚线
              drawDashLine(oGc, canvasw * 0.04 + 3, canvash / 3, canvasw - 5, canvash / 3, 2);
              drawDashLine(oGc, canvasw * 0.04 + 3, canvash * 0.82, canvasw - 5, canvash * 0.82, 2);
              //生成均价线
              priceLine(5, n, data, '#ff52fa');
              priceLine(10, n, data, '#f5bc49');
              priceLine(20, n, data, '#599ced');
              priceLine(60, n, data, '#888888');

              function priceLine(num, spot, data, color) {
                var arr = [],
                  arr1 = [],
                  avg_price = [];
                for (var i = 0; i < data.data.length; i++) {
                  arr.push((data.data[i][4]).toFixed(2));
                }
                for (i = num; i <= data.data.length; i++) {
                  var a = 0;
                  for (var j = 1; j <= num; j++) {
                    a += parseFloat(arr[i - j]);
                  }
                  arr1.push((a / num).toFixed(2));
                }
                for (i = 1; i < nlength + 1; i++) {
                  if (maxk < data.data[n - i][2]) {
                    maxk = data.data[n - i][2];
                  }
                  if (maxk < arr1[n - num - nlength + i - 1]) {
                    maxk = arr1[n - num - nlength + i - 1];
                  }
                  //最大值
                  if (mink > data.data[n - i][3]) {
                    mink = data.data[n - i][3];
                  }
                  if (mink > arr1[n - num - nlength + i - 1]) {
                    mink = arr1[n - num - nlength + i - 1];
                  }
                  if (maxl < data.data[n - i][6]) {
                    maxl = data.data[n - i][6];
                  }
                  if (minl > data.data[n - i][6]) {
                    minl = data.data[n - i][6];
                  }
                }
                maxk = Number(maxk);
                mink = Number(mink);
                maxl = Number(maxl);
                minl = Number(minl);
                if (maxk === mink) {
                  mink = 0;
                }
                if (maxl === minl) {
                  minl = 0;
                }
                oGc.beginPath();
                oGc.strokeStyle = color;
                oGc.lineWidth = 5;
                if (maxk > arr1[(n - num - nlength)] && mink < arr1[(n - num - nlength)]) {
                  oGc.moveTo(canvasw * 0.04, canvash * 0.09 + (canvash * 0.46 / (maxk - mink)) * (maxk - arr1[n - num - nlength]));
                  avg_price.push(arr1[n - num - nlength]);
                } else {
                  avg_price[0] = 0;
                }
                //循环写均价下一个点的坐标
                for (i = 0; i < nlength; i++) {
                  if (maxk > arr1[(n - num - nlength + 1) + i] && mink < arr1[(n - num - nlength + 1) + i]) {
                    oGc.lineTo(canvasw * 0.04 + 5 + (i * lineleft), canvash * 0.09 + canvash * 0.46 / (maxk - mink) * (maxk - arr1[(n - num - nlength + 1) + i]));
                    avg_price[i] = arr1[(n - num - nlength + 1) + i];
                  } else {
                    avg_price[i] = 0;
                  }
                  if (i == nlength - 1) {
                    var avgpricenum;
                    arr1[(n - num - nlength + 1) + i] == undefined ? avgpricenum = 0 : avgpricenum = arr1[(n - num - nlength + 1) + i];
                    if (num == 5) drawfont('40px', oGc, 'MA' + num + ':' + avgpricenum, canvasw * 0.04, canvash * 0.05, '#ff52fa');
                    if (num == 10) drawfont('40px', oGc, 'MA' + num + ':' + avgpricenum, canvasw * 0.04 + canvasw / 4, canvash * 0.05, '#f5bc49');
                    if (num == 20) drawfont('40px', oGc, 'MA' + num + ':' + avgpricenum, canvasw * 0.04 + canvasw / 4 * 2, canvash * 0.05, '#599ced');
                    if (num == 60) drawfont('40px', oGc, 'MA' + num + ':' + avgpricenum, canvasw * 0.04 + canvasw / 4 * 3, canvash * 0.05, '#888888');
                  }
                }
                avg_priceArr.push(avg_price);
                oGc.stroke();
              }
              //生成文字
              drawfont('40px', oGc, (maxk).toFixed(2), canvasw * 0.04, canvash * 0.09 + 36);
              drawfont('40px', oGc, ((maxk - mink) / 2 + mink).toFixed(2), canvasw * 0.04, canvash / 3);
              drawfont('40px', oGc, (mink).toFixed(2), canvasw * 0.04, 335 * canvash / 600);
              drawfont('40px', oGc, unita(maxl), canvasw * 0.04, 2 * canvash / 3 + canvash * 0.02);

              drawfont('40px', oGc, unita((maxl / 2).toFixed(0)), canvasw * 0.04, canvash * 0.82);
              drawfont('40px', oGc, data.data[n - nlength][0], canvasw * 0.03, canvash * 1 + 30);
              drawfont('40px', oGc, data.data[n - 1][0], canvasw * 0.85, canvash * 1 + 30);
              drawfont('40px', oGc, '成交量', canvasw * 0.04, canvash * 0.58 + 50);

              //生成日K线
              for (var i = nlength; i > 0; i--) {
                var codeinfo = [];
                var top = canvash * 0.09 + canvash * 0.46 / (maxk - mink) * (maxk - data.data[n - i][2]);
                var bottom = canvash * 0.09 + canvash * 0.46 / (maxk - mink) * (maxk - data.data[n - i][3]);
                var Recttop = canvash * 0.09 + canvash * 0.46 / (maxk - mink) * (maxk - data.data[n - i][1]);
                var Rectheight = canvash * 0.09 + canvash * 0.46 / (maxk - mink) * (maxk - data.data[n - i][4]);
                var Rectltop = canvash * 0.65 + canvash / 3 / (maxl - minl) * (maxl - data.data[n - i][6]);
                codeinfo.push(data.data[n - i][0]);
                codeinfo.push(data.data[n - i][1]);
                codeinfo.push(data.data[n - i][2]);
                codeinfo.push(data.data[n - i][3]);
                codeinfo.push(data.data[n - i][4]);
                codeinfo.push(data.data[n - i][5]);
                codeinfo.push(data.data[n - i][6]);
                codeinfo.push(data.data[n - i][7]);
                if (n - i - 1 < 0) {
                  codeinfo.push(data.data[n - i][4]); //存上一个的现价
                } else {
                  codeinfo.push(data.data[n - i - 1][4]); //存上一个的现价
                }
                codeinfoArr.push(codeinfo);
                maxMinObj.maxk = maxk;
                maxMinObj.mink = mink;
                oGc.beginPath();
                oGc.strokeStyle = '#f60300';
                oGc.fillStyle = '#f60300';
                if (data.data[n - i][1] > data.data[n - i][4]) {
                  Recttop = Recttop + Rectheight;
                  Rectheight = Recttop - Rectheight;
                  Recttop = Recttop - Rectheight;
                  oGc.strokeStyle = '#30ae0e';
                  oGc.fillStyle = '#30ae0e';
                } else {
                  oGc.strokeStyle = '#f60300';
                  oGc.fillStyle = '#f60300';
                }
                var height = Rectheight - Recttop;
                height = height == 0 ? 5 : height;
                oGc.lineWidth = 2;
                oGc.moveTo(0.5 + canvasw * 0.04 + Rectwidth / 2 + ((nlength - i) * lineleft), top);
                oGc.lineTo(0.5 + canvasw * 0.04 + Rectwidth / 2 + ((nlength - i) * lineleft), bottom);
                oGc.stroke();
                oGc.fillRect(canvasw * 0.04 + 1 + (nlength - i) * lineleft, Recttop, Rectwidth, height);
                if (canvash / 3 + canvash * 0.65 - Rectltop == 0) { // 量最低高度设置
                  oGc.fillRect(canvasw * 0.04 + 1 + (nlength - i) * lineleft, Rectltop, Rectwidth, -20);
                } else {
                  oGc.fillRect(canvasw * 0.04 + 1 + (nlength - i) * lineleft, Rectltop, Rectwidth, canvash / 3 + canvash * 0.65 - Rectltop);
                }
                oGc.closePath();
              }
              imgData = oGc.getImageData(0, 0, canvasw + 10, canvash + 100);
            }
          });
        }
      });
    };
  }]);

  //生成数字后面的单位的函数
  function unita(num) {
    var numLen = num.toString().length;
    if (numLen > 8) {
      num = num / 100000000;
      num = num.toFixed(2);
      return num + '亿';
    } else if (numLen > 4) {
      num = num / 10000;
      num = num.toFixed(2);
      return num + '万';
    } else {
      return num;
    }
  }

  //canvas生成虚线函数
  function getBeveling(x, y) {
    return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
  }

  function drawDashLine(context, x1, y1, x2, y2, dashLen) {
    context.beginPath();
    dashLen = dashLen === undefined ? 5 : dashLen;
    //得到斜边的总长度
    var beveling = getBeveling(x2 - x1, y2 - y1);
    //计算有多少个线段
    var num = Math.floor(beveling / dashLen);
    context.strokeStyle = '#dddddd';
    for (var i = 0; i < num; i++) {
      context[i % 2 == '0' ? 'moveTo' : 'lineTo'](x1 + (x2 - x1) / num * i, y1 + (y2 - y1) / num * i);
    }
    context.stroke();
    context.closePath();
  }

  function drawfont(size, ctx, fonts, x, y, color) {
    ctx.font = size + ' Microsoft YaHei';
    //设置字体填充颜色
    ctx.fillStyle = color || '#888888';
    //从坐标点(50,50)开始绘制文字
    ctx.fillText(fonts, x, y);
  }
})(angular);
